/**
 * 游戏场景剔除,
 * 关闭不在摄像机显示范围的RenderComponent,
 * 打开在摄像机显示范围的RenderComponent
 */

cc.Class({
  extends: cc.Component,
  properties: {
    camera: cc.Camera,
    boundingPadding: 50,
  },
  ctor() {
    this._renders = [];
  },
  
  onLoad() {
    this._init(this.node);
  },
  
  _init(levelNode) {
    this._renders = [];
    let excludeNodes = [];
    let renders = levelNode.getComponentsInChildren(cc.RenderComponent);
    for (let i = 0, len = renders.length; i < len; i++) {
      let render = renders[i];
      if (excludeNodes.indexOf(render.node) !== -1 || !render.node.active || !render.enabled)
        continue;
      
      this._renders.push(render);
    }
  },
  
  _doCulling() {
    let camera = this.camera ? this.camera : cc.Camera.main;
    //取摄像机可视范围
    let cameraWorldPos = camera.node.convertToWorldSpace(cc.Vec2.ZERO);
    if (!this.lastCameraWorldPos) {
      this.lastCameraWorldPos = cameraWorldPos;
    } else if (this.lastCameraWorldPos.equals(cameraWorldPos)) {
      //如果摄像机位置没有改变, 则直接退出
      return;
    }
    let cameraWidth = cc.winSize.width / camera.zoomRatio;
    let cameraHeight = cc.winSize.height / camera.zoomRatio;
    let cameraWorldLeft = cameraWorldPos.x - cameraWidth / 2 - this.boundingPadding;
    let cameraWorldRight = cameraWorldLeft + cameraWidth + this.boundingPadding * 2;
    let cameraWorldBottom = cameraWorldPos.y - cameraHeight / 2 - this.boundingPadding;
    let cameraWorldTop = cameraWorldBottom + cameraHeight + this.boundingPadding * 2;
    let cameraWorldBounding = cc.rect(cameraWorldLeft, cameraWorldBottom, cameraWorldRight - cameraWorldLeft, cameraWorldTop - cameraWorldBottom);
    
    for (let i = 0; i < this._renders.length;) {
      let render = this._renders[i];
      if (!cc.isValid(render.node)) {
        this._renders.splice(i, 1);
      } else {
        let boundingBox = render.node.getBoundingBoxToWorld();
        render.enabled = boundingBox.intersects(cameraWorldBounding);
        i++;
      }
    }
  },
  
  lateUpdate() {
    this._doCulling();
  }
});

